<?php
/**
 * Created by PhpStorm.
 * User: zhangyi
 * Date: 17/1/20
 * Time: 下午1:51
 */


namespace backend\components\behaviors;

use yii\base\InvalidCallException;
use yii\db\BaseActiveRecord;
use yii\behaviors\AttributeBehavior;
use yii;

class OperateBehavior extends AttributeBehavior
{

    public $operateAttribute = 'operate';

    public $value;


    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();

        if (empty($this->attributes)) {
            $this->attributes = [
                BaseActiveRecord::EVENT_BEFORE_INSERT => [$this->operateAttribute],
            ];
        }
    }

    protected function getValue($event)
    {
        if ($this->value === null) {

            if ( $attr = $this->owner->getAttribute($this->operateAttribute)) {

                return $attr;
            }

            if(!Yii::$app->user->isGuest) {
                return Yii::$app->user->identity->username;
            }
        }
        return parent::getValue($event);
    }

}